import { defineMock } from 'vite-plugin-mock-dev-server'
import os from 'os'
import {AjaxResult} from "@/entityType/AjaxResult.ts";

/**
 * 将子网掩码转换为 CIDR 前缀长度
 * @param {string} netmask 子网掩码（IPv4: 点分十进制；IPv6: 冒号分隔十六进制）
 * @param {string} family 地址族 ('IPv4' 或 'IPv6')
 * @returns {number} CIDR 前缀长度
 */
function getPrefixLength(netmask, family) {
    if (family === 'IPv4') {
        const octets = netmask.split('.').map(Number);
        let prefix = 0;
        for (const octet of octets) {
            if (octet === 0) break;
            const binary = octet.toString(2).padStart(8, '0'); // 转为8位二进制
            prefix += binary.replace(/0/g, '').length; // 统计1的个数
        }
        return prefix;
    } else if (family === 'IPv6') {
        const hexParts = netmask.split(':');
        let prefix = 0;
        for (const part of hexParts) {
            if (part === '') break; // 处理末尾空段（如 ffff:ffff:ffff:ffff::）
            const binary = parseInt(part, 16).toString(2).padStart(16, '0'); // 转为16位二进制
            const ones = binary.replace(/0/g, '').length;
            prefix += ones;
            if (ones < 16) break; // 当前段非全1时停止
        }
        return prefix;
    }
    return 0;
}

/**
 * 获取本机网络地址信息（IPv4/IPv6）
 * @returns {Object} 包含 ipv4 和 ipv6 数组的对象
 */
function getNetworkInfo() {
    const interfaces = os.networkInterfaces();
    const ipv4List = [];
    const ipv6List = [];

    for (const interfaceName of Object.keys(interfaces)) {
        const addresses = interfaces[interfaceName];
        for (const addr of addresses) {
            // 跳过回环地址
            if (addr.internal) continue;

            const { address, family, netmask, mac } = addr;
            const cidr = `/${getPrefixLength(netmask, family)}`;

            const entry = {
                接口名称: interfaceName,
                IP地址: address,
                子网掩码: netmask,
                MAC地址: mac,
                CIDR: address + cidr
            };

            if (family === 'IPv4') {
                ipv4List.push(entry);
            } else if (family === 'IPv6') {
                ipv6List.push(entry);
            }
        }
    }

    return { ipv4: ipv4List, ipv6: ipv6List };
}

// 执行并输出结果
const networkInfo = getNetworkInfo();

// console.log('===== IPv4 地址信息 =====');
// networkInfo.ipv4.forEach((info, index) => {
//     console.log(`条目 ${index + 1}:`);
//     console.log(`  接口: ${info['接口名称']}`);
//     console.log(`  IP: ${info['IP地址']}`);
//     console.log(`  子网掩码: ${info['子网掩码']}`);
//     console.log(`  MAC: ${info['MAC地址']}`);
//     console.log(`  CIDR: ${info['CIDR']}\n`);
// });
//
// console.log('===== IPv6 地址信息 =====');
// networkInfo.ipv6.forEach((info, index) => {
//     console.log(`条目 ${index + 1}:`);
//     console.log(`  接口: ${info['接口名称']}`);
//     console.log(`  IP: ${info['IP地址']}`);
//     console.log(`  子网掩码: ${info['子网掩码']}`);
//     console.log(`  MAC: ${info['MAC地址']}`);
//     console.log(`  CIDR: ${info['CIDR']}\n`);
// });

export default defineMock([
    {
        url: import.meta.env.VITE_BASE_API + '/ip/getipv4',
        method: 'POST',
        status: 200,
        // 可以使用函数，更灵活
        body: ()=>{
            return AjaxResult.success(networkInfo.ipv4.map((info) => info['IP地址']))
        }
    }
])
